﻿using System;
using System.Linq;
using System.Windows.Controls;
using MovieBuddy.Events;
using MovieModel.Model;
using MovieModel.Model.Common;
using MovieModel.Search;

namespace MovieBuddy.Views
{
    /// <summary>
    /// Interaction logic for MovieView.xaml
    /// </summary>
    public partial class MovieView : ISearchAcceptor
    {
        private Manager manager;

        public MovieView()
        {
            InitializeComponent();
            movieList1.SelectionChanged += MovieListSelectionChanged;
        }

        private void MovieListSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            movieDetailPanel1.Movies = movieList1.SelectedMovies;
        }

        private SearchQuery currentSearch;
        public SearchQuery CurrentSearch
        {
            get { return currentSearch; }
            set 
            { 
                currentSearch = value;
                if (Manager == null) return;
                movieList1.Movies = Manager.Movies.Values.Where(m => value == null || m.Matches(value));
            }
        }

        public Manager Manager
        {
            get { return manager; }
            set
            {
                if (manager != null && manager != value) throw new Exception("2 managers?  WTF.");
                if (manager != null) return;
                movieDetailPanel1.Manager = value;
                manager = value;
                movieList1.Movies = manager.Movies.Values.Where(m => CurrentSearch == null || m.Matches(CurrentSearch));
                manager.MovieAdded += MovieAdded;
                manager.MovieRemoved += MovieRemoved;
            }
        }

        private void MovieRemoved(object sender, ItemRemovedEventArgs<Movie> e)
        {
            if (CurrentSearch == null || e.RemovedItem.Matches(CurrentSearch))
                movieList1.Dispatcher.Invoke(() => movieList1.RemoveMovie(e.RemovedItem));
        }

        void MovieAdded(object sender, MovieModel.Model.Common.ItemAddedEventArgs<Movie> e)
        {
            if (CurrentSearch == null || e.AddedItem.Matches(CurrentSearch)) 
                movieList1.Dispatcher.Invoke(() => movieList1.AddMovie(e.AddedItem));
        }
    }

    public class MovieViewController : MovieBuddyViewController<MovieView>
    {
        public MovieViewController(Manager manager, MovieView control) : base(manager, control)
        {
            control.Manager = manager;
        }

        protected override void SearchChangedImpl(SearchEventArgs e)
        {
            Control.CurrentSearch = e.NewSearchValue;
        }

        public override ISearchAcceptor SearchAcceptor
        {
            get { return Control; }
        }
    }
}
